/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dusin.web.util;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author dusin
 */
public class JsonUtil {    
    public static String toDatagrid(List list){
        Map<String,Object> map = new HashMap<String,Object>();
        int size = 0;
        if(list==null){
            size = 0;
            map.put("success", true);
            map.put("total", 0);
            map.put("rows", new ArrayList());
        }else{
            map.put("success", true);
            map.put("total", list.size());
            map.put("rows", list);
        }
        Gson gson = new Gson();
        String result = gson.toJson(map);
        return result;
    }
    
    public static String toDatagrid(List list,int total){
        Map<String,Object> map = new HashMap<String,Object>();
        int size = 0;
        if(list==null){
            size = 0;
            map.put("success", true);
            map.put("total", 0);
            map.put("rows", new ArrayList());
        }else{
            map.put("success", true);
            map.put("total", total);
            map.put("rows", list);
        }
        Gson gson = new Gson();
        String result = gson.toJson(map);
        return result;
    }
    
    public static String toJsonText(Object obj){
        Gson gson = new Gson();
        String result = gson.toJson(obj);
        return result;
    }
    
    public static String createSuccessFileJsonResponse(String fileName) {
        StringBuilder sb = new StringBuilder();
        sb.append("{success:true,filename:'").append(fileName).append("'}");
        return sb.toString();
    }
    
    public static String createSuccessJsonResponse(String msg) {
        StringBuilder sb = new StringBuilder();
        sb.append("{success:true,msg:'").append(msg).append("'}");
        return sb.toString();
    }

    public static String createFailureJsonResponse(String msg) {
        StringBuilder sb = new StringBuilder();
        sb.append("{success:false,msg:'").append(msg).append("'}");
        return sb.toString();
    }
}
